package com.we.wfc.system.dto;

import com.we.wfc.common.base.BaseException;
import com.we.wfc.common.enums.AreaTypeEnum;
import com.we.wfc.common.enums.ReturnCode;
import com.we.wfc.common.utils.EnumUtil;
import com.we.wfc.system.entity.Area;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;

import javax.validation.constraints.NotBlank;
import java.util.Optional;

/**
 * 行政区划保存
 *
 * @author zhangby
 * @date 4/1/20 8:57 pm
 */
@Data
@Accessors(chain = true)
public class AreaSaveDto {
    @NotBlank(message = "请输入地区名称")
    private String name;
    private String shortName;
    @NotBlank(message = "请输入地区编码")
    private String code;
    @NotBlank(message = "上级地区不能为空")
    private String parentId;

    public Area convert(Area parentArea) {
        Area area = new Area();
        BeanUtils.copyProperties(this, area);
        // 查询父级记录
        Optional.ofNullable(parentArea).orElseThrow(() -> new BaseException(ReturnCode.PARENT_RECORD_NOT_EXIST));
        // 设置类型
        if (AreaTypeEnum.OTHER.equals(parentArea.getType())) {
            area.setType(AreaTypeEnum.OTHER.getValue());
        } else {
            int type = Integer.parseInt(parentArea.getType()) + 1;
            AreaTypeEnum areaTypeEnum = EnumUtil.initEnum(AreaTypeEnum.class, String.valueOf(type));
            area.setType(Optional.ofNullable(areaTypeEnum).orElse(AreaTypeEnum.OTHER).getValue());
        }
        // 设置父类ids
        area.setParentIds(area.getParentIds() + area.getId() + ",");
        return area;
    }
}
